package cn.edu.njust.advice;


import cn.edu.njust.pojo.bo.RestResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一响应处理
 *
 * @author wangs
 * @date 2025/5/1 19:37
 * @since 3.0.0
 */
@RestControllerAdvice(basePackages = "cn.edu.njust.controller")
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType, Class selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {

        // 如果已经是RestResult类型，直接返回
        if (body instanceof RestResult) {
            return body;
        }

        // 处理void返回类型
        if (body == null && returnType.getParameterType() == Void.TYPE) {
            return RestResult.success();
        }

        return RestResult.success(body);
    }
}
